<template>
  <view class="user-page">
    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <view class="user-avatar">
        <image
          :src="userInfo.avatar || '/static/images/default-avatar.png'"
          class="avatar-image"
          mode="aspectFill"
        />
      </view>
      <view class="user-details">
        <view class="user-name">{{ userInfo.nickname || "点击登录" }}</view>
        <view class="user-location" v-if="userInfo.location">
          <uni-icons type="location" size="14" color="#999999" />
          <text class="location-text">{{ userInfo.location }}</text>
        </view>
      </view>
      <view class="login-btn" @click="handleLogin" v-if="!isLoggedIn">
        <text class="login-text">登录</text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-item" @click="goToMyGoods">
        <text class="stat-number">{{ userStats.publishCount }}</text>
        <text class="stat-label">我的发布</text>
      </view>
      <view class="stat-item" @click="goToMyFavorites">
        <text class="stat-number">{{ userStats.favoriteCount }}</text>
        <text class="stat-label">我的收藏</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ userStats.viewCount }}</text>
        <text class="stat-label">浏览量</text>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view class="menu-item" @click="goToMyGoods">
          <view class="menu-left">
            <uni-icons type="goods" size="20" color="#07C160" />
            <text class="menu-text">我的发布</text>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC" />
        </view>
        <view class="menu-item" @click="goToMyFavorites">
          <view class="menu-left">
            <uni-icons type="heart" size="20" color="#FF6B6B" />
            <text class="menu-text">我的收藏</text>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC" />
        </view>
        <view class="menu-item" @click="goToHistory">
          <view class="menu-left">
            <uni-icons type="clock" size="20" color="#4FC3F7" />
            <text class="menu-text">浏览历史</text>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC" />
        </view>
      </view>

      <view class="menu-group">
        <view class="menu-item" @click="goToSettings">
          <view class="menu-left">
            <uni-icons type="gear" size="20" color="#9C27B0" />
            <text class="menu-text">设置</text>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC" />
        </view>
        <view class="menu-item" @click="goToAbout">
          <view class="menu-left">
            <uni-icons type="info" size="20" color="#FF9800" />
            <text class="menu-text">关于我们</text>
          </view>
          <uni-icons type="right" size="16" color="#CCCCCC" />
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section" v-if="isLoggedIn">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { getUserInfo, wxLogin } from "../../api/user";
import { userInfoStorage, tokenStorage } from "../../utils/storage";
import type { UserInfo, UserStats } from "../../types/user";

// 用户信息
const userInfo = reactive<UserInfo>({
  id: "",
  nickname: "",
  avatar: "",
  location: "",
});

// 用户统计信息
const userStats = reactive<UserStats>({
  publishCount: 0,
  soldCount: 0,
  favoriteCount: 0,
  viewCount: 0,
});

// 登录状态
const isLoggedIn = ref(false);

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 从本地存储获取用户信息
    const localUserInfo = userInfoStorage.get();
    if (localUserInfo) {
      Object.assign(userInfo, localUserInfo);
      isLoggedIn.value = true;

      // 获取最新的用户统计信息
      await loadUserStats();
    }
  } catch (error) {
    console.error("加载用户信息失败:", error);
  }
};

// 加载用户统计信息
const loadUserStats = async () => {
  try {
    // TODO: 调用API获取用户统计信息
    // const response = await getUserStats()
    // Object.assign(userStats, response.data)

    // 模拟数据
    userStats.publishCount = 12;
    userStats.favoriteCount = 8;
    userStats.viewCount = 156;
  } catch (error) {
    console.error("加载用户统计信息失败:", error);
  }
};

// 处理登录
const handleLogin = async () => {
  try {
    // 微信登录
    uni.login({
      provider: "weixin",
      success: async (loginRes) => {
        try {
          // TODO: 调用后端登录接口
          // const response = await wxLogin({ code: loginRes.code })
          // tokenStorage.set(response.data.token)
          // userInfoStorage.set(response.data.userInfo)

          // 模拟登录成功
          const mockUserInfo = {
            id: "123",
            nickname: "微信用户",
            avatar: "/static/images/default-avatar.png",
            location: "北京市朝阳区",
          };

          Object.assign(userInfo, mockUserInfo);
          userInfoStorage.set(mockUserInfo);
          tokenStorage.set("mock-token");
          isLoggedIn.value = true;

          uni.showToast({
            title: "登录成功",
            icon: "success",
          });

          await loadUserStats();
        } catch (error) {
          console.error("登录失败:", error);
          uni.showToast({
            title: "登录失败",
            icon: "none",
          });
        }
      },
      fail: (error) => {
        console.error("微信登录失败:", error);
        uni.showToast({
          title: "登录失败",
          icon: "none",
        });
      },
    });
  } catch (error) {
    console.error("登录异常:", error);
  }
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储
        userInfoStorage.remove();
        tokenStorage.remove();

        // 重置用户信息
        Object.assign(userInfo, {
          id: "",
          nickname: "",
          avatar: "",
          location: "",
        });

        // 重置统计信息
        Object.assign(userStats, {
          publishCount: 0,
          favoriteCount: 0,
          viewCount: 0,
        });

        isLoggedIn.value = false;

        uni.showToast({
          title: "已退出登录",
          icon: "success",
        });
      }
    },
  });
};

// 跳转到我的发布
const goToMyGoods = () => {
  if (!isLoggedIn.value) {
    handleLogin();
    return;
  }
  uni.navigateTo({
    url: "/pages/user/my-goods",
  });
};

// 跳转到我的收藏
const goToMyFavorites = () => {
  if (!isLoggedIn.value) {
    handleLogin();
    return;
  }
  uni.navigateTo({
    url: "/pages/user/my-favorites",
  });
};

// 跳转到浏览历史
const goToHistory = () => {
  uni.showToast({
    title: "功能开发中",
    icon: "none",
  });
};

// 跳转到设置
const goToSettings = () => {
  uni.showToast({
    title: "功能开发中",
    icon: "none",
  });
};

// 跳转到关于我们
const goToAbout = () => {
  uni.showToast({
    title: "功能开发中",
    icon: "none",
  });
};
</script>

<style lang="scss" scoped>
.user-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.user-info-section {
  background: linear-gradient(135deg, #07c160 0%, #05a050 100%);
  padding: 60rpx 30rpx 40rpx;
  display: flex;
  align-items: center;
  color: #ffffff;
}

.user-avatar {
  margin-right: 30rpx;
}

.avatar-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.user-location {
  display: flex;
  align-items: center;
  opacity: 0.8;
}

.location-text {
  font-size: 24rpx;
  margin-left: 5rpx;
}

.login-btn {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 15rpx 30rpx;
  border-radius: 30rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
}

.login-text {
  font-size: 28rpx;
  color: #ffffff;
}

.stats-section {
  background-color: #ffffff;
  margin: -20rpx 30rpx 20rpx;
  border-radius: 16rpx;
  padding: 40rpx 0;
  display: flex;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.stat-number {
  font-size: 40rpx;
  font-weight: bold;
  color: #07c160;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
}

.menu-section {
  padding: 0 30rpx;
}

.menu-group {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f8f8f8;
  }
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-text {
  font-size: 32rpx;
  color: #333333;
  margin-left: 20rpx;
}

.logout-section {
  padding: 40rpx 30rpx;
}

.logout-btn {
  width: 100%;
  height: 80rpx;
  background-color: #ffffff;
  color: #ff4444;
  font-size: 32rpx;
  border: 2rpx solid #ff4444;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    background-color: #fff5f5;
  }
}
</style>
